package com.yj.mvc.web.servlet.resource;

import cn.hutool.core.util.StrUtil;
import org.dom4j.Element;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import java.util.List;

public class WebXmlResourceParse  extends  XmlResource{

    private ServletConfig servletConfig;

    public WebXmlResourceParse(String path) {
        super(path);
        doParse();
    }

    public void setServletConfig(ServletConfig servletConfig) {
        this.servletConfig = servletConfig;
    }


    public void doParse() {
        while (super.hasNext()){
            Element element = (Element) super.next();
            String servletName = element.element("servlet-name").getTextTrim();
            String servletClass = element.element("servlet-class").getTextTrim();
            ServletContext servletContext = servletConfig.getServletContext();

            servletContext.addServlet(servletName, servletClass);

            Element initParamElement = element.element("init-param");
            if (initParamElement!= null) {
                List<Element> initParamList = initParamElement.elements("param-value");
                for (Element param : initParamList) {
                    String paramName = param.element("param-name").getTextTrim();
                    String paramValue = param.element("param-value").getTextTrim();
                    servletContext.setInitParameter(paramName, paramValue);
                }
            }

            String loadOnStartUp = element.element("load-on-startup").getTextTrim();
            if (StrUtil.isNotEmpty(loadOnStartUp)){
                servletContext.setInitParameter("loadOnStartUp", loadOnStartUp);
            }
        }
    }

    public static void main(String[] args) {
        WebXmlResourceParse webXmlResourceParse = new WebXmlResourceParse("resources/web.xml");
    }
}
